package com.example.casper.jnuexperiment2025.dataop;

import android.content.Context;
import com.example.casper.jnuexperiment2025.Book;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class DataPersistence {

    private static final String FILE_NAME = "book_data.dat";

    public void saveData(Context context, List<Book> books) {
        try (ObjectOutputStream oos = new ObjectOutputStream(context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE))) {
            oos.writeObject(books);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<Book> loadData(Context context) {
        try (ObjectInputStream ois = new ObjectInputStream(context.openFileInput(FILE_NAME))) {
            return (List<Book>) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>(); // Return empty list if file not found or error occurs
        }
    }
}